<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class Baimiao extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $key = $bean->getSecretKey();
        $platform_id = $bean->getSupplierNum();
        $array = [
            'mobile'        => $bean->getAccount(),
            'userorderno'   => $platform_id. $bean->getOrderNo(),//订单号
            'timestamp'     => millisecondTimestamp(),
            'productid'     => $bean->getGoodsId(), //商品编码
            'security'      => $key,
            'platformid'    => $platform_id
        ];
        ksort($array);
        $sign = urldecode(http_build_query($array));
        $array['sign'] = strtoupper(md5($sign));
        $array['cburl'] =$bean->getNotifyUrl(); //异步回调地址
        $array['mobile'] = encryptWithOpenssl($array['mobile'], $key, 'DES-ECB');
        $array['productid'] = encryptWithOpenssl($array['productid'], $key, 'DES-ECB');

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('resultcode', '');
        $order_sn = preg_replace('/\D/s', '', $request->input('userorderno', ''));
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['00000', '20017']))->setRechargeSuccess($status == '00000');
    }

    /**
     * @return JsonResponse
     */
    public function apiNotifySuccess(): JsonResponse
    {
        return response()->json(['resultcode'=>'0', 'resultdescription'=>'succeed']);
    }
}
